package com.yuxl.admin.manager.auth.socket.controller;

import com.yuxl.admin.common.security.annotation.NoAuth;
import com.yuxl.admin.common.socket.domain.SocketInMessage;
import com.yuxl.admin.common.socket.service.WebSocketService;
import com.yuxl.admin.common.socket.utils.SocketMessageUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.reactive.socket.WebSocketSession;
import reactor.core.publisher.Mono;
import java.util.Map;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/websocket")
@Tag(name = "实时通知模块", description = "websocket 操作")
public class WebSocketController {

    private final WebSocketService webSocketService;
    private final SocketMessageUtil socketMessageUtil;

    @NoAuth
    @Operation(summary = "向所有连接的WebSocket客户端发送消息")
    @PostMapping("/send")
    public Mono<ResponseEntity<String>> sendMessage(@RequestBody SocketInMessage message) {
        return socketMessageUtil.sendMessageToAllUsers(message)
                .then(Mono.just(ResponseEntity.ok("消息已发送给所有在线客户端")))
                .onErrorResume(e -> {
                    log.error("发送消息时发生错误", e);
                    return Mono.just(ResponseEntity.internalServerError().body("发送消息时发生错误"));
                });
    }

    @NoAuth
    @Operation(summary = "向指定用户连接的所有WebSocket客户端发送消息")
    @PostMapping("/sendMessageToUser")
    public Mono<ResponseEntity<String>> sendMessageToUser(@RequestBody SocketInMessage message) {
        String to = message.getTo();
        return socketMessageUtil.sendMessageToUser(message)
                .map(success -> {
                    if (success) {
                        return ResponseEntity.ok("消息已成功发送给用户 " + to + " 的所有活跃会话");
                    } else {
                        return ResponseEntity.badRequest().body("无法发送消息给用户 " + to + " 或用户没有活跃的WebSocket会话");
                    }
                });
    }

    @NoAuth
    @Operation(summary = "获取所有用户的WebSocket连接信息")
    @GetMapping("/connections")
    public Mono<ResponseEntity<Map<String, List<String>>>> getAllConnections() {
        Map<String, List<WebSocketSession>> allSessions = webSocketService.getAllSessions();
        Map<String, List<String>> connectionInfo = allSessions.entrySet().stream()
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        entry -> entry.getValue().stream()
                                .filter(WebSocketSession::isOpen)
                                .map(WebSocketSession::getId)
                                .collect(Collectors.toList())
                ));
        log.debug("获取到所有用户的WebSocket连接信息: {}", connectionInfo);
        return Mono.just(ResponseEntity.ok(connectionInfo));
    }
}
